<template>
    <SelectEquip v-if="selectEquipVisible" @confirm="selectConfirm" @cancel="selectEquipVisible = false"></SelectEquip>
    <div class="e-form" v-else>
        <div class="tabs" v-if="Object.keys(formData).length != 0">
             <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                 <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="固定资产盘点明细" name="planDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <div style="width: 100%" class="form">
                                <el-form ref="form" :model="formData.fixedAssetsCheck" label-width="200px">
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="盘点编号：">
                                                <span>{{ formData.fixedAssetsCheck.billNo }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="年度：">
                                                <el-select
                                                    v-model="formData.fixedAssetsCheck.year"
                                                    placeholder="请选择"
                                                >
                                                    <el-option
                                                        v-for="(
                                                            item
                                                        ) in budgetYearList"
                                                        :key="item"
                                                        :label="item"
                                                        :value="item"
                                                    >
                                                    </el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="使用（保管）人：">
                                                <el-input v-model="formData.fixedAssetsCheck.preserver"  readonly>
                                                    <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="selectHandling"></i>
                                                </el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="机构：">
                                                <span>{{ formData.fixedAssetsCheck.orgName }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="24">
                                            <el-form-item label="状态：">
                                                <span>{{ statusLable(formData.fixedAssetsCheck.state) }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </el-form>
                            </div>
                        </div>
                    </div>

                    <div id="planDetailCon">
                        <div class="tabs-title" id="planDetail">固定资产盘点明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <el-button  class="btn-blue" @click="smmary">汇总</el-button>
                                    <el-button class="btn-greenYellow" @click="selectEquipVisible = true">新增</el-button>
                                    <el-button   @click="deletePlanList">删除</el-button>
                                </div>
                            </div>
                            <el-form :model="formData.fixedAssetsCheckDtlList" ref="from" :rules="rules">
                                <el-table
                                    ref="planTable"
                                    :data="formData.fixedAssetsCheckDtlList"
                                    border
                                    style="width: 100%"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    :cell-class-name="cellClsNm"
                                    @selection-change="planTableSelect"
                                >
                                    <el-table-column type="selection" width="55" align="center">
                                    </el-table-column>
                                    <el-table-column
                                        prop="equipmentNo"
                                        label="设备编号"
                                        align="center"
                                        min-width="200"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        prop="equipmentName"
                                        label="设备名称"
                                        width="200"
                                        align="center"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        prop="specificationModel"
                                        label="规格型号"
                                        width="200"
                                        align="center"
                                    >
                                        <template slot-scope="{ row   }">
                                            <el-input v-model="row.specificationModel" clearable></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="originalPrice"
                                        label="原值（元）"
                                        width="200"
                                        align="center"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        prop="buyTime"
                                        label="购置日期"
                                        width="200"
                                        align="center"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        prop="depositSite"
                                        label="存放地点"
                                        width="200"
                                        align="center"
                                    >
                                        <template slot-scope="{ row }">
                                            <el-input v-model="row.depositSite"  readonly>
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy"></i>
                                            </el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="state"
                                        label="设备状态"
                                        width="200"
                                        align="center"
                                    >
                                        <template slot-scope="{ row }">
                                            <span>{{ equipStatus.find(x=>x.value === row.state).label  }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="checkResults"
                                        label="清查结果"
                                        width="200"
                                        align="center"
                                    >
                                        <template slot-scope="{ row }">
                                            <el-select v-model="row.checkResults"  :disabled="row.isCollect" >
                                            <el-option :value="item.value" :label="item.label" v-for="item,index in checkResultsList" :key="index" ></el-option>
                                            </el-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="checkExplain"
                                        label="清查说明"
                                        width="200"
                                        align="center"
                                    >
                                        <template slot-scope="{ row }">
                                            <el-input v-model="row.checkExplain" clearable></el-input>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-form>

                        </div>
                    </div>

                    <div id="attachCon">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" bucketName="testModule" />
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <el-table
                                :data="tableData"
                                border
                                style="width: 100%"
                                @cell-mouse-enter="cellMouseEnter"
                                @cell-mouse-leave="cellMouseLeave"
                                :cell-class-name="cellClsNm"
                            >
                                <el-table-column prop="a1" label="审核级次" width="200"> </el-table-column>
                                <el-table-column prop="a" label="审核人" width="200"> </el-table-column>
                                <el-table-column prop="b" label="审核人岗位" width="200"> </el-table-column>
                                <el-table-column prop="c" label="通知时间" width="200"> </el-table-column>
                                <el-table-column prop="c" label="审核时间" width="200"> </el-table-column>
                                <el-table-column prop="c" label="审核意见" width="200"> </el-table-column>
                            </el-table>
                        </div>
                        <ComPagination />
                    </div>
                </div>
            </el-tabs>
        </div>
         <div class="buttons">
                <el-button type="primary" size="small" class="btn-blue"
                    >打印</el-button
                >
                <el-button
                    type="primary"
                    size="small"
                    class="btn-delete"
                    @click="deleteBIll"
                    v-if="state === '0'"
                    >删除</el-button
                >
                <el-button
                    type="primary"
                    size="small"
                    class="btn-blue"
                    @click="nullifyeBIll"
                    v-if="state === '1'"
                    >作废</el-button
                >
                <el-button type="primary" size="small" class="btn-blue"
                    >审核</el-button
                >
                <el-button type="primary" size="small" class="btn-blue"
                    >撤回</el-button
                >
                <el-button
                    type="primary"
                    size="small"
                    class="btn-blue"
                    @click="submit"
                    v-if="state === '0'"
                    >保存并提交</el-button
                >
                <el-button
                    type="primary"
                    size="small"
                    class="btn-blue"
                    @click="preserve"
                     v-if="state === '0'"
                    >保存</el-button
                >
                <el-button size="small" @click="handleClose">取消</el-button>
            </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import SelectEquip from '@/pages/equipment/equipPlan/configPlan/configPlanDialog/selectEquip.vue'
import { selectName } from '@/api/equip/popupCallback.js'
import $ from 'jquery'
import request from '@/api/equip/dailyManagement.js'
import { formatDate } from '@/utils/common.js'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
export default {
    components: {
        SelectEquip,
        AttachComp,
    },
    data () {
        return {
            // dialogVisible: false,
            // fullscreen: false,
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            selectEquipVisible: false,
            tableData: [],
            planTableData: [{ 'd': 123, c: '' }],
            value: '',
            textarea: '',
            formData: {
                //基础信息
                'fixedAssetsCheck': {
                    'billNo': '',
                    'fixedAssetsCheckId': '',
                    'gmtCreate': '',
                    'gmtModified': '',
                    'nullifyCreated': '',
                    'nullifyCreator': '',
                    'nullifyCreatorId': '',
                    'nullifyDesciption': '',
                    'nullifyReason': '',
                    'orgId': '',
                    'orgName': '',
                    'preserver': '',
                    'preserverId': '',
                    'state': '0',
                    'year': ''
                },
                'fixedAssetsCheckDtlList': {}
            },
            billid: '',
            planSelect: [], //固定资产盘点明细选择项
            workIndex: 0,
            typeList: [ //申请类型
                { value: 0, label: '全部' },
                { value: 1, label: '报废' },
                { value: 2, label: '处置' },
            ],
            processModeList: [ //处置方式
                { value: 0, label: '自行处置' },
                { value: 1, label: '公开转让' },
                { value: 2, label: '公开招标' },
            ],
            scrapTypeList: [ //报废类型
                { value: true, label: '正常报废' },
                { value: false, label: '异常报废' },
            ],
            checkResultsList: [ //清查结果
                { value: 0, label: '账物相符' },
                { value: 1, label: '有账无物' },
                { value: 2, label: '有物无账' },
            ],
            rules: {
                specificationModel: [{ required: true, message: '规格型号不能为空', trigger: 'blur' }],
                checkExplain: [{ required: true, message: '清查说明不能为空', trigger: 'blur' }],
            },
            budgetYearList: [], //年度
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.contract.ctClassify.currencyForm, //币种
            equipStatus: state => state.equip.equipData.equipStatus//设备状态
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value == param)
                return obj.label
            }
        },
        //当前单据状态
        state () {
            return this.formData.fixedAssetsCheck.state
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.$route.query.billid
        },
    },

    created () {
        this.billid = this.$route.query.billid
        this.userId = localStorage.getItem('userId')
        // const date = new Date()
        // const year = date.getFullYear()
        // for(let i = 5;i--;i >= 0) {
        //     this.budgetYearList.push( new String(year - i) )
        // }
        this.getInfo()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'planDetail', 'attach', 'auditHistory']
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth
        this.screenHeight = document.documentElement.clientHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })

    },
    methods: {
        selectEquip ( index) {
            this.workIndex = index
            this.selectEquipVisible = true
        },
        getInfo () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.assetsInventoryBaseInfo(params).then(res=>{
                this.formData = res
                this.getPlanList()
            })
        },
        getPlanList () {
            const params = {
                id: this.billid,
            }
            request.assetsInventoryPlanInfo(params).then(res=>{
                this.formData.fixedAssetsCheckDtlList = res.fixedAssetsCheckDtlList
            })
        },
        getNowDate () {
            this.$set(
                this.formData,
                'applyTime',
                new Date()
                    .toLocaleDateString()
                    .replace(new RegExp('/', 'g'), '-')
            )
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            console.log('clickTabFlag: ', this.clickTabFlag)
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //固定资产盘点明细新增
        addPlanInfo () {
            const arr = this.formData.fixedAssetsCheckDtlList ? this.formData.fixedAssetsCheckDtlList : []
            const obj = {
                'billNo': '',
                'buyTime': '',
                'checkExplain': '',
                'checkResults': 0,
                'depositSite': '',
                'depositSiteId': '',
                'equipmentName': '',
                'equipmentNo': '',
                'fixedAssetsCheckDtlId': '',
                'fixedAssetsCheckId': '',
                'isCollect': '',
                'originalPrice': 0,
                'specificationModel': '',
                'state': 0
            }
            let date  = formatDate(new Date(), 'yyyy-MM-dd')
            obj.buyTime = date
            arr.push(obj)
            this.$set(this.formData, 'fixedAssetsCheckDtlList',  arr)
            console.log('fixedAssetsCheckDtlList', this.formData.fixedAssetsCheckDtlList)
        },
        //选择设备确认
        selectConfirm (data) {
            if(!data) return false
            const arr = this.formData.fixedAssetsCheckDtlList ? this.formData.fixedAssetsCheckDtlList : []
            data.forEach(x=>{
                const obj = {
                    'billNo': '',
                    'buyTime': '',
                    'checkExplain': '',
                    'checkResults': 0,
                    'depositSite': '',
                    'depositSiteId': '',
                    'equipmentName': '',
                    'equipmentNo': '',
                    'fixedAssetsCheckDtlId': '',
                    'fixedAssetsCheckId': '',
                    'isCollect': '',
                    'originalPrice': 0,
                    'specificationModel': '',
                    ...x,
                    'state': '0',
                }
                let date  = formatDate(new Date(), 'yyyy-MM-dd')
                obj.buyTime = date
                arr.push(obj)
            })
            this.$set(this.formData, 'fixedAssetsCheckDtlList',  arr)
            console.log('fixedAssetsCheckDtlList', this.formData.fixedAssetsCheckDtlList)
            console.log('fixedAssetsCheckDtlList', this.formData.fixedAssetsCheckDtlList)
            this.selectEquipVisible = false
        },
        //保存
        preserve () {
            request.assetsInventoryUpdate(this.formData).then(()=>{
                this.clientPop('suc', '保存成功', ()=>{ this.$router.push('/assetsInventoryList') })
            })
        },
        //提交
        submit () {
            request.assetsInventoryUpdate(this.formData).then(()=>{
                request.assetsInventoryCommit({ fixedAssetsCheckIdList: this.billid }).then(()=>{
                    this.$message.success('提交成功')
                    this.$router.push('/assetsInventoryList')
                })
            })

        },
        //删除
        deleteBIll () {
            this.clientPop('err', '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。', ()=>{
                request.assetsInventoryDelete({ fixedAssetsCheckIdList: this.billid }).then(()=>{
                    this.clientPop('suc', '删除成功', ()=>{ this.$router.push('/assetsInventoryList') })
                })
            })
        },
        //作废
        nullifyeBIll () {
            request.assetsInventoryNullify({ fixedAssetsCheckIdList: this.billid }).then(()=>{
                this.$message.success('作废成功')
                this.$router.push('/assetsInventoryList')
            })
        },
        //删除固定资产盘点明细列表
        deletePlanList () {
            this.planSelect.forEach(row=>{
                console.log('row', row.equipmentId)
                const index = this.formData.fixedAssetsCheckDtlList.findIndex(item=>{
                    return item.equipmentId == row.equipmentId
                })
                this.formData.fixedAssetsCheckDtlList.splice(index, 1)
            })

        },
        //获取固定资产盘点明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //取消
        handleClose () {
            this.$router.go(-1)
        },
        // 获取地址对应中文
        getAddrLabel (val) {
            console.log('getAddrLabel: ', val)
            this.formData.fixedAssetsCheck.acceptanceSiteList = val
        },
        //汇总
        smmary () {
            const params = {
                orgId: this.userInfo.orgInfo.orgId
            }
            request.assetsInventorSmmary(params).then(res=>{
                console.log('res', res)
            })
        },
        //选择经办人 (选择本机构用户)
        selectHandling () {
            selectName().then(res=>{
                this.formData.fixedAssetsCheck.preserver = res[0].userName
            })
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;

    /* .top {
    .left {
      padding: 20px;
      padding-top: 0px;
    }
  } */
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
